
using namespace System.Xml.Linq
using namespace System.Xml.XPath

$SourceCCAV = [System.Xml.Linq.XElement]::Load(
    "E:\Program Files (x86)\Steam\steamapps\common\Baldurs Gate 3\Data\Editor\Mods\Shared\CharacterCreation\CharacterCreationAppearanceVisuals.tbl"
)
$SourceCCAV.Add(
    [System.Xml.Linq.XElement]::Load(
        "E:\Program Files (x86)\Steam\steamapps\common\Baldurs Gate 3\Data\Editor\Mods\SharedDev\CharacterCreation\CharacterCreationAppearanceVisuals.tbl"
    ).Elements()
)

$replaceTable = @{}

$fieldsList = [System.Xml.XPath.Extensions]::XPathSelectElements($SourceCCAV, "/stat_objects/stat_object/fields/field[@name='Comment']/..")

foreach ($fields in $fieldsList) {
    $comment = [System.Xml.XPath.Extensions]::XPathSelectElement($fields, "./field[@name='Comment']").Attribute("value").Value
    $replaceTable[$comment] = [System.Xml.XPath.Extensions]::XPathSelectElement($fields, "./field[@name='DisplayName']")
}

$TargetCCAV = [System.Xml.Linq.XElement]::Load(
    "H:\Source\BD3\Mods\PanguEpoch2HumanVariant\Editor\CharacterCreation\CharacterCreationAppearanceVisuals.tbl",
    [LoadOptions]::PreserveWhitespace
)

$fieldsList = [System.Xml.XPath.Extensions]::XPathSelectElements($TargetCCAV, "/stat_objects/stat_object/fields/field[@name='Comment']/..")

foreach ($fields in $fieldsList) {
    $comment = [System.Xml.XPath.Extensions]::XPathSelectElement($fields, "./field[@name='Comment']").Attribute("value").Value
    $replaceTo = $replaceTable[$comment]
    if ($replaceTo -ne $null) {
        [System.Xml.XPath.Extensions]::XPathSelectElement($fields, "./field[@name='DisplayName']").ReplaceWith($replaceTo)
    }
}


$TargetCCAV.Save("result.tbl")

